package com.vinoxm.rss.subscribe;

import com.vinoxm.rss.model.RssResult;
import com.vinoxm.rss.model.RssTracker;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class TrackerHandler {
    public static List<RssTracker> torrentHandler(RssResult rssResult) {
        List<RssTracker> trackers = new ArrayList<>();
        String torrent = rssResult.getTorrent();
        if (torrent.startsWith("magnet:?xt=urn:btih:")) {
            int i = torrent.indexOf("&");
            if (i > -1) {
                rssResult.setTorrent(torrent.substring(20, i));
                String[] trs = torrent.substring(i).split("&");
                for (String tracker : trs) {
                    if (tracker.startsWith("tr=")) {
                        trackers.add(new RssTracker(tracker.replace("tr=", "")));
                    }
                }
            } else {
                rssResult.setTorrent(torrent.substring(20));
            }
        }
        return trackers;
    }

    public static List<RssTracker> torrentsHandler(List<RssResult> list) {
        Set<RssTracker> trackers = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            RssResult rssResult = list.get(i);
            rssResult.setId((long)i + 1);
            List<RssTracker> trs = torrentHandler(rssResult);
            if (trs.size() > 0) rssResult.setTrackers(trs.stream().map(RssTracker::getHost).collect(Collectors.toList()));
            trackers.addAll(trs);
        }
        return new ArrayList<>(trackers);
    }
}
